﻿using System;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.PRM.AppCode.Lib;

namespace mojoPortal.Web.RS.PRM.Controls
{
    public partial class ModalRentalAgreementControl : RSBaseUserControl
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
            }
        }

        public void ShowModal(int companyid, int propertyid, int leaseid)
        {
            lblMessage.Text = "";
            hfIsDirty.Value = "";
            hfLeaseID.Value = leaseid.ToString();
            hfPropertyID.Value = propertyid.ToString();
            ddlTenant.Visible = false;
            btnSave.Visible = true;
            btnReturn.Visible = true;
            LoadPaymentDueDays();
            RSPRMDataLookupLoader.LoadTypeDDL(companyid, "LEASETERM_CAT", ddlLeaseTerm);
            RSPRMDataLookupLoader.LoadStatusDDL(companyid, "LEASE_CAT", ddlLeaseStatus);
            RSPRMDataLookupLoader.LoadTenantDDL(companyid, propertyid, leaseid, ddlTenant);
            if (companyid > 0 && propertyid > 0 && leaseid > 0)
            {
                ddlTenant.Visible = true;
                LoadLeaseDataByID(companyid, propertyid, leaseid);
            }
            else
            {
                ResetRentalAgreementFields();
            }
            mpeModalCreateRentalAgreement.Show();
        }
        protected void ddlTenant_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            hfTenantID.Value = ddlTenant.SelectedValue.ToString();
            int tenantid = int.Parse(hfTenantID.Value);

            RSUserIdentity userIdentity = GetRSUserIdentity();
            String sql = "exec rs_uspGetTenantByID @CompanyID, @TenantID";
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;
            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sql, myConnection);
            SqlDataReader myDataReader;

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@CompanyID";
            param.Value = userIdentity.RSCompanyId;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@TenantID";
            param.Value = tenantid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            if (myDataReader.HasRows)
            {
                myDataReader.Read();
                txtRelationship.Text = myDataReader["Relationship"].ToString();
                txtEmail.Text = myDataReader["Email"].ToString();
                txtFirstName.Text = myDataReader["FirstName"].ToString();
                txtHomePhone.Text = myDataReader["HomePhone"].ToString();
                txtMiddleName.Text = myDataReader["MiddleName"].ToString();
                txtMobile.Text = myDataReader["Mobile"].ToString();
                txtLastName.Text = myDataReader["LastName"].ToString();
                txtFax.Text = myDataReader["Fax"].ToString();
                txtDLN.Text = myDataReader["DLN"].ToString();
                txtSSN.Text = myDataReader["SSN"].ToString();
                txtDLNState.Text = myDataReader["DLNState"].ToString();
                if (myDataReader["BirthDay"] != DBNull.Value)
                {
                    DateTime dt = Convert.ToDateTime(myDataReader["BirthDay"].ToString());
                    txtBirthDay.Text = dt.ToShortDateString();
                }

            }
            myConnection.Close();
        }
        private void LoadLeaseDataByID(int companyid, int propertyid, int leaseid)
        {
            String sql = "exec rs_uspGetPropertyLeaseByID @CompanyID, @PropertyID, @LeaseID";
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;
            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sql, myConnection);
            SqlDataReader myDataReader;

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@CompanyID";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@PropertyID";
            param.Value = propertyid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@LeaseID";
            param.Value = leaseid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            if (myDataReader.HasRows)
            {
                myDataReader.Read();

                //Tenant 
                if (myDataReader["TenantID"] != DBNull.Value)
                {
                    hfTenantID.Value = myDataReader["TenantID"].ToString();
                    ddlTenant.SelectedValue = hfTenantID.Value;
                }
                txtRelationship.Text = myDataReader["Relationship"].ToString();
                txtEmail.Text = myDataReader["Email"].ToString();
                txtFirstName.Text = myDataReader["FirstName"].ToString();
                txtHomePhone.Text = myDataReader["HomePhone"].ToString();
                txtMiddleName.Text = myDataReader["MiddleName"].ToString();
                txtMobile.Text = myDataReader["Mobile"].ToString();
                txtLastName.Text = myDataReader["LastName"].ToString();
                txtFax.Text = myDataReader["Fax"].ToString();
                txtDLN.Text = myDataReader["DLN"].ToString();
                txtSSN.Text = myDataReader["SSN"].ToString();
                txtDLNState.Text = myDataReader["DLNState"].ToString();
                //Lease
                if (myDataReader["StatusID"] != DBNull.Value)
                {
                    ddlLeaseStatus.SelectedValue = myDataReader["StatusID"].ToString();
                }
                txtDepositAmount.Text = myDataReader["DepositAmount"].ToString();
                txtLeaseAmount.Text = myDataReader["LeaseAmount"].ToString();
                txtResidentQty.Text = myDataReader["ResidentQty"].ToString();
                txtHouseholdIncome.Text = myDataReader["HouseholdIncome"].ToString();
                ddlPaymentDueDay.SelectedValue = myDataReader["PaymentDueDay"].ToString();
                
                if (myDataReader["TermTypeID"] != DBNull.Value)
                {
                    string termtypeid = myDataReader["TermTypeID"].ToString();
                    ddlLeaseTerm.SelectedValue = termtypeid;
                }
                
                if (myDataReader["BirthDay"] != DBNull.Value)
                {
                    DateTime dt = Convert.ToDateTime(myDataReader["BirthDay"].ToString());
                    txtBirthDay.Text = dt.ToShortDateString();
                }
                if (myDataReader["CheckInDt"] != DBNull.Value)
                {
                    DateTime dt = Convert.ToDateTime(myDataReader["CheckInDt"].ToString());
                    txtMoveInDate.Text = dt.ToShortDateString();
                }
                if (myDataReader["CheckOutDt"] != DBNull.Value)
                {
                    DateTime dt = Convert.ToDateTime(myDataReader["CheckOutDt"].ToString());
                    txtMoveOutDate.Text = dt.ToShortDateString();
                }
            }
            myConnection.Close();
        }

        protected void btnModalOK_Click(Object sender, EventArgs e)
        {
            mpeModalCreateRentalAgreement.Hide();
            if (hfIsDirty.Value == "1")
            {
                string activetab = "1";
                Response.Redirect(RedirectToCurrentURL(activetab));
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                int propertyid = hfPropertyID.Value == "" ? 0 : int.Parse(hfPropertyID.Value);
                int leaseid = hfLeaseID.Value == "" ? 0 : int.Parse(hfLeaseID.Value);
                int tenantid = hfTenantID.Value == "" ? 0 : int.Parse(hfTenantID.Value);
                
                string relationship = txtRelationship.Text;
                string firstname = txtFirstName.Text;
                string lastname = txtLastName.Text;
                string middlename = txtMiddleName.Text;
                string homephone = txtHomePhone.Text;
                string mobile = txtMobile.Text;
                string fax = txtFax.Text;
                string email = txtEmail.Text;

                bool ishead = chkIsHead.Checked;
                int paymentdueday = int.Parse(ddlPaymentDueDay.SelectedValue);
                int termtypeid = int.Parse(ddlLeaseTerm.SelectedValue);
                int statusid = int.Parse(ddlLeaseStatus.SelectedValue);

                string birthday = txtBirthDay.Text;
                string dln = txtDLN.Text;
                string ssn = txtSSN.Text;
                string dlnstate = txtDLNState.Text;
                string depositamount = txtDepositAmount.Text;
                string leaseamount = txtLeaseAmount.Text;
                string moveindate = txtMoveInDate.Text;
                string moveoutdate = txtMoveOutDate.Text;
                string residentqty = txtResidentQty.Text;
                string householdincome = txtHouseholdIncome.Text;

                SqlCommand sqlCmd = new SqlCommand();
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@IsHead", SqlDbType.Bit, 0, ParameterDirection.Input, ishead);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Relationship", SqlDbType.NVarChar, 15, ParameterDirection.Input, relationship);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@FirstName", SqlDbType.NVarChar, 50, ParameterDirection.Input, firstname);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@LastName", SqlDbType.NVarChar, 50, ParameterDirection.Input, lastname);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@MiddleName", SqlDbType.NVarChar, 50, ParameterDirection.Input, middlename);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@HomePhone", SqlDbType.NVarChar, 15, ParameterDirection.Input, homephone);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Mobile", SqlDbType.NVarChar, 15, ParameterDirection.Input, mobile);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Fax", SqlDbType.NVarChar, 15, ParameterDirection.Input, fax);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Email", SqlDbType.NVarChar, 50, ParameterDirection.Input, email);

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@PropertyID", SqlDbType.Int, 0, ParameterDirection.Input, propertyid);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@LeaseID", SqlDbType.Int, 0, ParameterDirection.Input, leaseid);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@TenantID", SqlDbType.Int, 0, ParameterDirection.Input, tenantid);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 30, ParameterDirection.Input, userIdentity.RSCurrentUser);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, userIdentity.RSCompanyId);

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@DepositAmount", SqlDbType.Float, 0, ParameterDirection.Input, depositamount);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@LeaseAmount", SqlDbType.Float, 0, ParameterDirection.Input, leaseamount);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@PaymentDueDay", SqlDbType.Int, 0, ParameterDirection.Input, paymentdueday);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CheckInDt", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(moveindate));
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CheckOutDt", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(moveoutdate));
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@TermTypeID", SqlDbType.Int, 0, ParameterDirection.Input, termtypeid);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ResidentQty", SqlDbType.Int, 0, ParameterDirection.Input, residentqty);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@StatusID", SqlDbType.Int, 0, ParameterDirection.Input, statusid);

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@IsActive", SqlDbType.Bit, 0, ParameterDirection.Input, propertyid);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@HouseholdIncome", SqlDbType.Int, 0, ParameterDirection.Input, householdincome);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@BirthDay", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(birthday));
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@DLN", SqlDbType.NVarChar, 20, ParameterDirection.Input, dln);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@DLNState", SqlDbType.NVarChar, 50, ParameterDirection.Input, dlnstate);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@SSN", SqlDbType.NVarChar, 12, ParameterDirection.Input, ssn);

                SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveRentalAgreement");
                SQLHelper.ExecuteScalarCmd(sqlCmd);

                int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                lblMessage.Text = "Lease Saved Successfully";
                btnSave.Visible = false;
                btnReturn.Visible = false;
            }
        }

        private void LoadPaymentDueDays()
        {
            ddlPaymentDueDay.Items.Clear();
            for (int i = 0; i < 31; i++)
            {
                ddlPaymentDueDay.Items.Add(i.ToString());
            }
        }
        private void ResetRentalAgreementFields()
        {
            btnSave.Visible = true;
            lblMessage.Text = "";
            btnReturn.Visible = true;
            ddlTenant.SelectedValue = "0";
            txtRelationship.Text = "";
            txtEmail.Text = "";
            txtFirstName.Text = "";
            txtHomePhone.Text = "";
            txtMiddleName.Text = "";
            txtMobile.Text = "";
            txtLastName.Text = "";
            txtFax.Text = "";
            txtBirthDay.Text = "";
            txtDLN.Text = "";
            txtSSN.Text = "";
            txtDLNState.Text = "";
            ddlLeaseStatus.SelectedValue = "0";
            txtDepositAmount.Text = "";
            txtLeaseAmount.Text = "";
            txtMoveInDate.Text = "";
            txtMoveOutDate.Text = "";
            txtResidentQty.Text = "";
            txtHouseholdIncome.Text = "";
            ddlPaymentDueDay.SelectedValue = "0";
            ddlLeaseTerm.SelectedValue = "0";
        }
        private string RedirectToCurrentURL(string activetab)
        {
            var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
            nameValues.Set("selindex", activetab);
            string url = Request.Url.AbsolutePath;
            string updatedQueryString = "?" + nameValues.ToString();
            url = url + updatedQueryString;
            return url;
        }
    }
}